//
//  EditCompanyAddressViewController.m
//  有材网
//
//  Created by 肖扬 on 16/1/30.
//  Copyright © 2016年 肖扬. All rights reserved.
//

#import "EditCompanyAddressViewController.h"
#import "purchaseButton.h"
#import "XlineView.h"
#import "EditHUDView.h"
@interface EditCompanyAddressViewController ()<UIPickerViewDataSource,UIPickerViewDelegate,UITextFieldDelegate>{
    int selectBtn;
    NSMutableArray *provinceArray;
    NSMutableArray *cityArray;
    NSMutableArray *thirdArray;
    NSTimer *timer_;
}
@property (nonatomic,strong)NSMutableDictionary *submitDic;
@end

@implementation EditCompanyAddressViewController
@synthesize submitDic,province,city,address;
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.leftBtn addTarget: self action: @selector(goBackAction) forControlEvents: UIControlEventTouchUpInside];
    [self.rightBtn setTitle:@"完成" forState:0];
    [self.rightBtn addTarget:self action:@selector(submitClick:) forControlEvents:UIControlEventTouchUpInside];
    provinceArray = [NSMutableArray array];
    cityArray = [NSMutableArray array];
    self.submitDic = [NSMutableDictionary dictionary];
    UIView *tempView = [self createViewFrame:CGRectMake(0, 74, SWIDTH, 129) bgColor:[UIColor whiteColor] tag:10];
    [self.view addSubview:tempView];
    
    NSArray *arr = [NSArray arrayWithObjects:@"省份",@"城市", nil];
    for (int i = 0; i < [arr count]; i++) {
        purchaseButton *button = [[purchaseButton alloc]initWithFrame:CGRectMake(0, i*43, SWIDTH, 43)];
        button.tempLab.text = [arr objectAtIndex:i];
        [button setBackgroundColor:[UIColor clearColor]];
        [button setTag:300+i];
        [button addTarget:self action:@selector(selectClick:) forControlEvents:UIControlEventTouchUpInside];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button setTitleColor:GRAYColor forState:0];
        [tempView addSubview:button];
        XlineView *lineView = [[XlineView alloc]initWithFrame:CGRectMake(10, 42.5, SWIDTH - 20, 0.5)];
        lineView.backgroundColor = [UIColor grayColor];
        lineView.alpha = 0.2;
        [button addSubview:lineView];
    }
    UIButton *button = (UIButton *)[tempView viewWithTag:300];
    UIButton *button1 = (UIButton *)[tempView viewWithTag:301];
    if (![Unity isBlankString:self.province]) {
        for (int i = 0; i < [[appStatus shareAppStatus].provinceArray count]; i++) {
            NSMutableDictionary *dic = [[appStatus shareAppStatus].provinceArray objectAtIndex:i];
            if ([[dic objectForKey:@"id"] isEqualToString:self.province]) {
                [button setTitle:[dic objectForKey:@"city"] forState:0];
            }
        }
        for (int i = 0; i < [[appStatus shareAppStatus].cityArray count]; i++) {
            NSMutableDictionary *dic = [[appStatus shareAppStatus].cityArray objectAtIndex:i];
            if ([[dic objectForKey:@"id"] isEqualToString:self.city]) {
                [button1 setTitle:[dic objectForKey:@"city"] forState:0];
            }
        }
    }
    UITextField *tempTextField = [self createTextFieldFrame:CGRectMake(10, 86, SWIDTH-20, 43) bgColor:[UIColor whiteColor] tag:102 keyBoardType:0];
    tempTextField.font = [UIFont systemFontOfSize:14];
    tempTextField.delegate = self;
    tempTextField.textAlignment = NSTextAlignmentLeft;
    tempTextField.placeholder = @"详细地址(选填)";
    if (![Unity isBlankString:self.address]) {
        tempTextField.text = self.address;
    }
    [tempView addSubview:tempTextField];
    [tempTextField becomeFirstResponder];
    // Do any additional setup after loading the view.
}
-(void)submitClick:(UIButton *)sender{
    UIView *tempView = (UIView *)[self.view viewWithTag:10];
    UIButton *button = (UIButton *)[tempView viewWithTag:300];
    UIButton *button1 = (UIButton *)[tempView viewWithTag:301];
    if (![[button currentTitle] isEqualToString:@""]&& ![[button1 currentTitle] isEqualToString:@""]) {
        TIME
        HEADDIC(nowTime, SETCOMPANY);
        UITextField *textfield = (UITextField *)[tempView viewWithTag:102];
        [textfield resignFirstResponder];
        [self.submitDic setObject:textfield.text forKey:@"address"];
        NSString *result = [Unity requestSomeApiData:HEAD withBody:self.submitDic];
        NSMutableDictionary *json = [result objectFromJSONString];
        if ([[json objectForKey:@"err_code"] integerValue]==0) {
            EditHUDView *hudView = [[EditHUDView alloc]initWithFrame:CGRectMake(0, 64, SWIDTH, VHEIGHT)];
            hudView.backgroundColor = [UIColor clearColor];
            hudView.tag = 1010;
            hudView.alertLab.text = [json objectForKey:@"err_message"];
            [self.view addSubview:hudView];
            timer_ = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(doTime) userInfo:nil repeats:NO];
            
        }else{
            SHOW_ALERT([json objectForKey:@"err_message"]);
        }
    }
}
-(void)doTime
{
    //alert过1秒自动消失
    [self resetTimer];
    [self removeHudView];
}
-(void)removeHudView{
    EditHUDView *hudView = (EditHUDView *)[self.view viewWithTag:1010];
    if (hudView) {
        [hudView removeFromSuperview];
        hudView = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}
-(void) resetTimer
{
    if (timer_) {
        [timer_ invalidate];
        timer_ = nil;
    }
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 255) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)selectClick:(purchaseButton *)sender{
    UIView *tempView2 = (UIView *)[self.view viewWithTag:10];
    if (sender.tag != 300) {
        purchaseButton *button = (purchaseButton *)[tempView2 viewWithTag:300];
        if ([[button currentTitle]isEqualToString:@""]||[button currentTitle]==nil) {
            SHOW_ALERT(@"请先选择省份");
            return;
        }
    }
    selectBtn = sender.tag;
    [self returnPickerView];
}
-(void)returnPickerView{
    UIView *tempView2 = (UIView *)[self.view viewWithTag:10];
    UITextField *textField = (UITextField *)[tempView2 viewWithTag:102];
    [textField resignFirstResponder];
    UIView *tempView1 = (UIView *)[self.view viewWithTag:220];
    UIPickerView *pickV = (UIPickerView *)[tempView1 viewWithTag:221];
    if (pickV) {
        [pickV removeFromSuperview];
        pickV = nil;
    }
    UIToolbar *toolbar = (UIToolbar *)[tempView1 viewWithTag:223];
    if (toolbar) {
        [toolbar removeFromSuperview];
        toolbar = nil;
    }
    if (tempView1) {
        [tempView1 removeFromSuperview];
        tempView1 = nil;
    }
    UIView *tempView = (UIView *)[self createViewFrame:CGRectMake(0, SHEIGHT - 260, SWIDTH, 260) bgColor:[UIColor whiteColor] tag:220];
    [self.view addSubview:tempView];
    
    //创建工具栏
    NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:3];
    UIBarButtonItem *confirmBtn = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(confirmPickView)];
    UIBarButtonItem *flexibleSpaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(pickerHide)];
    [items addObject:cancelBtn];
    [items addObject:flexibleSpaceItem];
    [items addObject:confirmBtn];
    
    UIPickerView *tempPicker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 44, SWIDTH, 216)];
    tempPicker.tag = 221;
    tempPicker.delegate = self;
    tempPicker.dataSource = self;
    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, 44)];
    toolBar.tag = 223;
    toolBar.hidden = NO;
    toolBar.barStyle = UIBarStyleDefault;
    toolBar.items = items;
    [tempView addSubview:toolBar];
    [tempView addSubview:tempPicker];
}
-(void)confirmPickView{
    UIView *tempView2 = (UIView *)[self.view viewWithTag:10];
    UIView *tempView = (UIView *)[self.view viewWithTag:220];
    UIPickerView *pickV = (UIPickerView *)[tempView viewWithTag:221];
    int select = [pickV selectedRowInComponent:0];
    purchaseButton *button = nil;
    if (selectBtn == 300) {
        button = (purchaseButton *)[tempView2 viewWithTag:300];
        purchaseButton *button1 = (purchaseButton *)[tempView2 viewWithTag:301];
        NSDictionary *dic = [[appStatus shareAppStatus].provinceArray objectAtIndex:select];
        [button setTitle:[dic objectForKey:@"city"] forState:0];
        [self.submitDic removeAllObjects];
        [self.submitDic setObject:[dic objectForKey:@"id"] forKey:@"province"];
        [button1 setTitle:@"" forState:0];
    }else{
        button = (purchaseButton *)[tempView2 viewWithTag:301];
        NSDictionary *dic = [thirdArray objectAtIndex:select];
        [button setTitle:[dic objectForKey:@"city"] forState:0];
        [self.submitDic setObject:[dic objectForKey:@"id"] forKey:@"city"];
    }
    if (tempView) {
        [tempView removeFromSuperview];
        tempView = nil;
    }
}
-(void)pickerHide{
    [self removePickerView];
}

-(void)removePickerView{
    UIView *tempView = (UIView *)[self.view viewWithTag:220];
    if (tempView) {
        [tempView removeFromSuperview];
        tempView = nil;
    }
}

#pragma mark --
#pragma mark--UIPickerViewDataSource
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (selectBtn == 300) {
        return [[appStatus shareAppStatus].provinceArray count];
    }else{
        return [[appStatus shareAppStatus].cityArray count];
    }
    return 0;
}


#pragma mark--
#pragma mark--UIPickerViewDelegate
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (selectBtn == 300) {
        NSDictionary *dic = [[appStatus shareAppStatus].provinceArray objectAtIndex:row];
        return [dic objectForKey:@"city"];
    }else{
        UIView *tempView2 = (UIView *)[self.view viewWithTag:10];
        purchaseButton *tempButton = (purchaseButton *)[tempView2 viewWithTag:selectBtn - 1];
        NSString *cityId = [NSString string];
        NSMutableArray *arr = [NSMutableArray array];
        for (int i = 0; i <[[appStatus shareAppStatus].provinceArray count]; i++) {
            NSMutableDictionary *dic = [[appStatus shareAppStatus].provinceArray objectAtIndex:i];
            if ([[dic objectForKey:@"city"] isEqualToString:tempButton.titleLabel.text]) {
                cityId = [dic objectForKey:@"id"];
            }
        }
        for (int k = 0; k < [[appStatus shareAppStatus].cityArray count]; k++) {
            NSMutableDictionary *dic = [[appStatus shareAppStatus].cityArray objectAtIndex:k];
            if ([[dic objectForKey:@"province_id"] isEqualToString:cityId]) {
                [arr addObject:dic];
            }
        }
        thirdArray = arr;
        NSDictionary *dic = [thirdArray objectAtIndex:row];
        return [dic objectForKey:@"city"];
    }
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSLog(@"row is %d,Component is %d",row,component);
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
